package com.zh.common.ktx

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Build
import android.text.InputFilter
import android.text.InputType
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.zh.common.R
import com.zh.common.net.exception.ApiException
import com.zh.common.net.http.netService
import com.zh.common.net.requestApi
import com.zh.common.utils.DoubleUtils
import com.zh.common.utils.GlideManager
import com.zh.common.utils.InputMoneyFilter
import com.zh.common.utils.InputNameFilterNoSpace
import com.zh.config.dialog.TipsDialog
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class ViewKtx {
}

/**
 * 去掉ViewPager2滑动阴影
 */
fun ViewPager2.disEnabledOverScrollMode() {
    (this.getChildAt(0) as? RecyclerView)?.overScrollMode = View.OVER_SCROLL_NEVER
}

/**
 * 设置SpanUtils点击部分文字生效的背景色及事件响应
 */
fun TextView.spanClickBackground(color: Int = R.color.transparent.color()) {
    this.movementMethod = LinkMovementMethod.getInstance()
    this.highlightColor = color
}

/**
 * 设置TextView的Drawable
 */
fun TextView.setTextImgRes(
    leftImage: Int = 0, topImage: Int = 0, rightImage: Int = 0, bottomImage: Int = 0
) {
    this.setCompoundDrawablesWithIntrinsicBounds(leftImage, topImage, rightImage, bottomImage)
}

/**
 * 设置TextView颜色资源
 */
fun TextView.setTextColorRes(resId: Int) {
    setTextColor(ContextCompat.getColor(context, resId))
}

/**
 * 姓名输入 输入6位数  限制表情符号 不限制空格
 */
fun EditText.nameFormatNoSpace(maxLen: Int = 6) {
    this.filters = arrayOf(InputNameFilterNoSpace(), InputFilter.LengthFilter(maxLen))
}

/**
 * 金额输入 数字输入键盘  限制2位小数  默认9位数字
 * @param canNegative  能输入负数
 */
fun EditText.moneyFormat(canNegative: Boolean = false, maxLen: Int = 9) {
    this.inputType =
        if (canNegative) InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED or InputType.TYPE_NUMBER_FLAG_DECIMAL
        else InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
    this.filters = arrayOf(InputMoneyFilter(canNegative, maxLen))
}

/**
 * 加载图片
 */
fun ImageView.loadUrl(url: Any, defaultRes: Int = 0) {
    GlideManager.loadUrl(url, this, defaultRes)
}

/**
 * 加载头像
 */
fun ImageView.loadAvatarUrl(url: Any, defaultRes: Int = 0) {
    GlideManager.loadAvatarUrl(url, this, defaultRes)
}

/**
 * 加载gif
 */
fun ImageView.loadGifUrl(url: Any) {
    GlideManager.loadGifUrl(url, this)
}

/**
 * 动态添加布局
 */
fun Context.inflate(
    @LayoutRes id: Int, root: ViewGroup? = null, attachToRoot: Boolean = false
): View = LayoutInflater.from(this).inflate(id, root, attachToRoot)

/**
 * 点击事件的View扩展
 */
fun View.clickSingleListener(click: View.OnClickListener) = setOnClickListener {
    if (DoubleUtils.isFastDoubleClick(this)) return@setOnClickListener
    click.onClick(it)
}

/**
 * 判断RecyclerView滑动到了顶部或者底部
 */
@RequiresApi(Build.VERSION_CODES.M)
fun RecyclerView.scrollToTopOrBottomListener(callBack: (top: Boolean, bottom: Boolean) -> Unit) {
    this.setOnScrollChangeListener { _, _, _, _, _ ->
        //在底部
        val isScrollBottom = !this.canScrollVertically(1)
        //在顶部
        val isScrollTop = !this.canScrollVertically(-1)
        callBack.invoke(isScrollTop, isScrollBottom)
    }
}

/**
 * 上传图片
 */
fun View.uploadFile(
    path: String,
    onSuccess: (response: String?) -> Unit,
    onError: ((e: ApiException) -> Unit)? = null
) {
    val file = File(path)
    //上传图片需要MultipartBody
    val requestBody = RequestBody.create("image/jpg".toMediaTypeOrNull(), file)
    val body = MultipartBody.Part.createFormData("file", file.name, requestBody)

    this.requestApi({ netService().uploadFile(body, "1") }, true, error = { code, msg ->
        if (onError != null) onError(ApiException(code, msg)) else msg.toast()
    }) {
        onSuccess(it)
    }
}

/**
 * 文本内容相对于某一点居中
 *
 * @param canvas  画布
 * @param paint   画笔
 * @param text    文本内容
 * @param centerX x轴方向中心点
 * @param centerY y轴方向中心点
 */
fun Canvas.drawTextInCenter(paint: Paint, text: String, centerX: Float, centerY: Float) {
    val bottom = paint.fontMetrics.bottom
    this.drawText(
        text,
        (centerX - measureTextWidth(text, paint) * 0.5).toFloat(),
        (0.5 * measureTextHeight(paint) - bottom + centerY).toFloat(),
        paint
    )
}

private fun measureTextWidth(text: String, paint: Paint): Float {
    return paint.measureText(text)
}

private fun measureTextHeight(paint: Paint): Float {
    val fm = paint.fontMetrics
    return fm.bottom - fm.top
}


fun Context.showTipsDialog(
    title: String = "",
    content: String = "",
    sureTv: String = "确定",
    cancelTv: String = "取消",
    call: () -> Unit
) {
    TipsDialog(this, title, content, sureTv, cancelTv, call).show()
}

fun Context.showTipsDialog(
    content: String = "",
    sureTv: String = "确定",
    cancelTv: String = "取消",
    call: () -> Unit
) {
    TipsDialog(this, "", content, sureTv, cancelTv, call).show()
}


